package com.wavehi.exce;

import com.wavehi.pojo.Person;
import org.junit.Test;

import java.lang.annotation.Annotation;
import java.lang.reflect.*;

/**
 * @Author WaveHi
 * @Date 24/8/2021 下午 10:02
 * @Version 1.0
 * @Contact HJBWaveHi@163.com
 * @Description 类对应地Class实例
 */
public class ClassDemo {

    public static void main(String[] args) {

        Person person1 = new Person();

        Class<? extends Person> aClass1 = person1.getClass();

        Class<Person> aClass = (Class<Person>)person1.getClass();

        Class<Person> personClass = Person.class;

        System.out.println(aClass1 == personClass);

        System.out.println(aClass == personClass);

    }

    @Test
    public void testGetMethod() throws IllegalAccessException, InstantiationException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException {

        //获取Person对应的Class对象
        Class<Person> personClass = (Class<Person>)Class.forName("com.wavehi.pojo.Person");

        System.out.println(personClass.getName());

        //获取指定的构造器
        Constructor<Person> constructor = personClass.getDeclaredConstructor(String.class, int.class);
        System.out.println(constructor);
        System.out.println(constructor.getName());

        //获取方法
        Method[] declaredMethods = personClass.getDeclaredMethods();

        //获取方法的权限修饰符
        int modifiers = declaredMethods[0].getModifiers();
        System.out.println(Modifier.toString(modifiers));

        //获取属性
        Field[] declaredFields = personClass.getDeclaredFields();

        //获取注解
        Annotation[] declaredAnnotations = personClass.getDeclaredAnnotations();


        //通过构造器获取对象
        constructor.setAccessible(true);
        Person tom = constructor.newInstance("Tom", 12);
        System.out.println(tom.getAge());

        //获取包名
        System.out.println(personClass.getPackage());

    }

}
